package com.jm.controller;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.jm.common.util.entity.Phone;
import com.jm.common.util.entity.R;
import com.jm.common.util.entity.SelectCondition;
import com.jm.pojo.User;
import com.jm.pojo.dto.UserDto;
import com.jm.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.CachePut;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;

@RestController
@RequestMapping("/user")
public class UserController {

    @Autowired
    private UserService userService;

    @PostMapping("/sendMsg")
    public R<String> sendMessage(@RequestBody Phone phone) {
        boolean b = userService.sendMessage(phone);
        if (b) return R.success("验证码发送成功");
        return R.error("验证码发送错误");
    }

    @PostMapping("/login")
    public R<String> loginByCode(@RequestBody Phone phone, HttpServletRequest request) {
        String phoneNumber = phone.getPhone();
        boolean b = userService.checkPhoneNumber(phone);
        if (b) {
//            查询数据库是否是新用户
            boolean result = userService.checkUserIsExits(phoneNumber);
            if (!result) {
//                新用户
                boolean save = userService.save(new User(phoneNumber));
                if (!save) return R.error("新建用户失败,请重试");
            }
//            根据号码查询用户
            User user = userService.getUserByPhone(phoneNumber);
            if (user == null) return R.error("该号码未查询到正确的用户信息,请重试");
            if (user.getStatus() == 0) return R.error("该用户已被封禁，请联系管理员解除封禁");
            request.getSession().setAttribute("user", user.getId());
            return R.success("登录成功");
        }
        return R.error("验证码不对,登录失败");
    }

    @PostMapping("/login/password")
    public R<String> loginByPassword(@RequestBody Phone phone, HttpServletRequest request) {
        String phoneNumber = phone.getPhone();
        String password = phone.getPassword();
        User user = userService.getUserByPhone(phoneNumber);
        if (user != null) {
            boolean result = userService.checkUsernameAndPassword(phoneNumber, password);
            if (result) {
                if (user.getStatus() == 0) return R.error("该用户已被封禁，请联系管理员解除封禁");
                request.getSession().setAttribute("user", user.getId());
                return R.success("登陆成功");
            }
            return R.error("登陆失败,密码错误");
        }
        return R.error("该手机号未被注册,请使用验证码登录");
    }

    @GetMapping
    @Cacheable(value = "UserCache",key = "#result.data")
    public R<IPage<User>> selectByPage(SelectCondition condition) {
        IPage<User> page = userService.selectByPageCondition(condition);
        return R.success(page);
    }

    @GetMapping("/page")
    @Cacheable(value = "UserCache",key = "#result.data")
    public R<IPage<UserDto>> selectByPageCondition(SelectCondition condition) {
//        分页查询
        IPage<User> userIPage = userService.selectByPageCondition(condition);
//        将查询到的列表转化为Toy的扩展对象
        IPage<UserDto> toyDtoIPage = userService.toDto(userIPage);
        return R.success(toyDtoIPage);
    }

    @GetMapping("/{id}")
    @Cacheable(value = "UserCache",key = "#id")
    public R<User> selectUserById(@PathVariable Long id) {
        User user = userService.getById(id);
        return R.success(user);
    }

    @GetMapping("/phone/{phone}")
    @Cacheable(value = "UserCache",key = "#phone")
    public R<User> selectUserByPhone(@PathVariable String phone) {
        User userByPhone = userService.getUserByPhone(phone);
        return R.success(userByPhone);
    }

    @PutMapping
    @CacheEvict(value = "UserCache",allEntries = true)
    public R<String> updateUser(@RequestBody User user) {
        boolean b = userService.updateById(user);
        if (b) return R.success("修改成功");
        return R.error("修改失败");
    }

    @PostMapping()
    @CacheEvict(value = "UserCache",allEntries = true)
    public R<String> addUser(@RequestBody User user) {
        boolean save = userService.save(user);
        if (save) return R.success("添加成功");
        return R.error("添加失败");
    }
}
